import axios from 'axios'

// 创建axios实例
const request = axios.create({
  baseURL:'/api' ,
  timeout: 10000
})

// 请求拦截器
request.interceptors.request.use(config => {
  const userStr = sessionStorage.getItem('user')
  if (userStr) {
    try {
      const user = JSON.parse(userStr)
      if (user.token) {
        config.headers.Authorization = `Bearer ${user.token}`
      }
    } catch (e) {
      console.error('解析用户信息失败', e)
    }
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截器
request.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response) {
      const { status, data } = error.response
      const errorMap = {
        401: '未授权，请重新登录',
        403: '拒绝访问',
        404: '接口不存在',
        500: data?.msg || '服务器错误'
      }
      console.error(errorMap[status] || `请求错误: ${status}`)
    }
    return Promise.reject(error)
  }
)

export default request